package log

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/golang-jwt/jwt/v4"
	"shenmawl/internal/dao"
	"shenmawl/internal/model/entity"
	"shenmawl/utility"
	"strings"
)

type LogsClaims struct {
	Username string
	jwt.RegisteredClaims
}

func (l *Logs) GetLoginLogList(ctx context.Context) (logList []entity.SysLoginLog, count int, err error) {
	// 创建一个空的SysUser实体用于存储查询结果
	logList = make([]entity.SysLoginLog, 0)
	var tokenString string

	// 从上下文中获取HTTP请求对象，并尝试获取名称为"jwt"的Cookie
	token, _ := g.RequestFromCtx(ctx).Request.Cookie("jwt")

	if strings.HasPrefix(token.String(), "jwt=") { //检查字符串是否以jwt=开头
		tokenString = strings.TrimPrefix(token.String(), "jwt=") //删除前缀"jwt="
	}
	tokenClaims, _ := jwt.ParseWithClaims(tokenString, &LogsClaims{}, func(token *jwt.Token) (interface{}, error) {
		return utility.JwtKey, nil
	})

	if claims, ok := tokenClaims.Claims.(*LogsClaims); ok && tokenClaims.Valid {
		err = dao.SysLoginLog.Ctx(ctx).Where("user_name", claims.Username).ScanAndCount(&logList, &count, true)
	}

	//fmt.Println(gconv.String(&logList))
	// 返回查询到的用户信息和可能的错误
	return
}
